const fs = require('fs')
const path = require('path')
const http = require('http')

// 写法一：

// const server = http.createServer((req, res) => {
//   const { pathname } = new URL(req.url, 'http://127.0.0.1')
//   if (pathname === '/') {
//     const html = fs.readFileSync(path.resolve(__dirname, 'home.html'))
//     res.write(html)
//   } else if (pathname === '/home.css') {
//     const css = fs.readFileSync(path.resolve(__dirname, 'home.css'))
//     res.write(css)
//   } else if (pathname === '/home.js') {
//     const js = fs.readFileSync(path.resolve(__dirname, 'home.js'))
//     res.write(js)
//   } else {
//     res.statusCode = 404
//     res.write('404')
//   }
//   res.end()
// })
// server.listen(3000, () => {
//   console.log('启动成功！')
// })

// 写法二：

const server = http.createServer((req, res) => {
  const { pathname } = new URL(req.url, 'http://127.0.0.1')
  const filePath = __dirname + pathname
  fs.readFile(filePath, (err, data) => {
    if (err) {
      console.log('错误')
      return
    }
    res.write(data)
    res.end()
  })
})
server.listen(3000, () => {
  console.log('启动成功！')
})
